package org.testfire.realm.util;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.apache.commons.mail.SimpleEmail;
import org.apache.log4j.Logger;

/**
 * A simple mail class.
 * 
 * A very nice write up on using the Apache Mail API is available at:
 * http://www.builderau.com.au/program/java/soa/Sending_e_mail_in_Java_There_s_more_than_one_way/0,339024620,339222642,00.htm
 * Where DJ Walker-Morgan provides some code samples along with his article.
 *
 *
 *
 * @author Geoff M. Granum
 * @version 1.0
 *          Date: Nov 6, 2006
 *          Time: 6:35:06 PM
 */
public class Mailer
{



    private Mailer() {}

    public static void sendMessage( String toAddress, String messageBody )
    {
        new MailerThread( toAddress, messageBody ).start();
    }

    private static class MailerThread extends Thread
    {
        private String m_toAddress;

        private String m_messageBody;

        MailerThread( String toAddress, String messageBody )
        {
            m_toAddress = toAddress;
            m_messageBody = messageBody;
        }

        public void run()
        {
            try
            {
                InitialContext ic = new InitialContext();

                
                String snName = "java:comp/env/mail/testFireMailSession";
                Session session = (Session)ic.lookup( snName );
                Properties props = session.getProperties();
                String messageSubject = props.getProperty( "mail.registrationMessageSubject" );
                String fromName = props.getProperty( "mail.fromName" );
                String fromAddress = props.getProperty( "mail.fromAddress" );
                String smtpHost = props.getProperty("mail.host");
                String user = props.getProperty("mail.user");
                String pass = props.getProperty("mail.password");



                SimpleEmail email = new SimpleEmail();
                email.setHostName( smtpHost );
                email.setAuthentication( user, pass );
                email.setFrom( fromAddress, fromName );
                email.addTo( m_toAddress );
                email.setSubject( messageSubject );
                email.setMsg( m_messageBody );
                email.send();
            }
//            catch ( EmailException e )
//            {
//                e.printStackTrace();
//                Logger.getLogger( Mailer.class ).error( "", e );
//            }
            catch ( NamingException e )
            {
                Logger.getLogger( Mailer.class ).error( "", e );
            }
            catch(Exception e){
                Logger.getLogger( Mailer.class ).error( "", e );
            }
        }
    }


}
